package com.mk.settlement.mappers;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import com.mk.settlement.model.HotelModel;
import com.mk.settlement.model.SettlementRelation;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath*:spring/applicationContext*.xml" })
@Transactional
public class ImportHotelAndInitRelation {
    
    private Logger log = LoggerFactory.getLogger(ImportHotelAndInitRelation.class);
    
    @Resource
    private HotelModelMapper hotelModelMapper;
    
    @Resource
    private SettlementRelationMapper settlementRelationMapper;
    
    @Test
//    @Rollback(false)
    public void initRelation() {
        
        List<HotelModel> hotels = hotelModelMapper.getAll();
        
        int total = 0;
        
        for(HotelModel h : hotels) {
            
            SettlementRelation r1 = new SettlementRelation();
            
            r1.setSettlementRuleId(1);
            r1.setSettlementTargetId(h.getId());
            r1.setSettlementTargetName(h.getHotelname());
            r1.setCreateTime(new Date());
            r1.setSettlementThreshold(new BigDecimal(1000).setScale(2));
            
            try {
                int iResult = settlementRelationMapper.insert(r1);
                if (iResult > 0) {
                    total++;
                }
            } catch (DuplicateKeyException e) {
                log.info("酒店id:" + h.getId() + "已经存在于规则1的对应关系,继续.");
            } catch (Exception e) {
                log.error("插入酒店规则对应关系异常!", e);
            }
            SettlementRelation r2 = new SettlementRelation();
            
            r2.setSettlementRuleId(2);
            r2.setSettlementTargetId(h.getId());
            r2.setSettlementTargetName(h.getHotelname());
            r2.setCreateTime(new Date());
            r2.setSettlementThreshold(new BigDecimal(100).setScale(2));
            
            try {
                int iResult2 = settlementRelationMapper.insert(r2);
                if (iResult2 > 0) {
                    total++;
                }
            } catch (DuplicateKeyException e) {
                log.info("酒店id:" + h.getId() + "已经存在于规则2的对应关系,继续.");
            } catch (Exception e) {
                log.error("插入酒店规则对应关系异常!", e);
            }
        }
        
        log.info("共插入" + total + "条数据.");
    }

}
